package cate.game.role;

import cate.game.GameBody;
import cate.game.common.rpc.RpcListener4Game;
import cate.game.common.rpc.RpcSender4Game;
import cate.game.event.RoleEventPublisher;
import cate.game.framework.ISilenceSpanable;
import cate.game.log.GameLoggerFactory;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import org.slf4j.Logger;
import org.springframework.data.annotation.Transient;

public abstract class RoleDependent implements ISilenceSpanable , RoleEventPublisher {
    @Transient
    @JsonIgnore
    protected transient Logger logger;
    @Transient
    @JsonIgnore
    @Getter
    protected transient Role role;

    protected GameBody game() {
        return this.role.getGame();
    }

    protected RpcSender4Game rpcSend() {
        return game().rpcSend();
    }

    protected RpcListener4Game rpcRecv() {
        return game().rpcRecv();
    }

    public RoleDependent() {

    }

    public RoleDependent(Role role) {
        this.role = role;
        if(role != null && role.getGame() != null){
            this.logger = GameLoggerFactory.getLogger(role.getGame(), this.getClass());
        }
    }

    public void initialize(Role role) {
        this.role = role;
        if(role != null && role.getGame() != null){
            this.logger = GameLoggerFactory.getLogger(role.getGame(), this.getClass());
        }
    }


    /** 玩家进入游戏时 */
    public void onEnter(){
    }

    /** 玩家离线时 */
    protected void offline(){

    }

    public void offlineSafe(){
        try{
            offline();
        } catch (Exception e){
            logger.error("{}模块下线异常", getClass().getName(), e);
        }
    }

    /** 玩家创建时 */
    public void onCreate(){

    }

    /**
     * 实现
     * @param silence silence
     */
    @Override
    public void onDaySpan(boolean silence) {

    }

    /**
     * 调用
     * @param silence silence
     */
    public final void onDaySpanSafe(boolean silence){
        try{
            onDaySpan(silence);
        }catch(Exception e){
            logger.error("{}跨天异常", getClass().getName(), e);
        }
    }

    /**
     * 实现
     * @param silence silence
     */
    @Override
    public void onWeekSpan(boolean silence) {

    }

    /**
     * 调用
     * @param silence silence
     */
    public final void onWeekSpanSafe(boolean silence){
        try{
            onWeekSpan(silence);
        }catch(Exception e){
            logger.error("{}跨周异常", getClass().getName(), e);
        }
    }

    /**
     * 实现
     * @param silence silence
     */
    @Override
    public void onMonthSpan(boolean silence) {

    }

    /**
     * 调用
     * @param silence silence
     */
    public final void onMonthSpanSafe(boolean silence){
        try{
            onMonthSpan(silence);
        }catch(Exception e){
            logger.error("{}跨月异常", getClass().getName(), e);
        }
    }

    protected long now() {
        return role.getGame().time.now();
    }

}

